﻿using System;
using System.Configuration;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.OleDb;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Deployment.Application;


namespace Budget
{
    public partial class Form1 : Form
    {
        public string connstr;
        Income income;
        Expenses exp;
        public string month;
        public int monthnum;
        public int year;
        int date_col_width = 100;
        public const string dbName = "budget.accdb";
        public Form1()
        {
            InitializeComponent();
            this.Icon = new Icon("make-money.ico");
            button1.Visible = false;
            btnRefresh.Visible = false;
            //do this to trigger the changed event.
            dateTimePicker1.Value = DateTime.Now;
            year = dateTimePicker1.Value.Year;
            month = dateTimePicker1.Value.ToString("MMMM");
            GetUserDataPath();
        }

        private void button1_Click(object sender, EventArgs e)
        {         
        }

        private void RefreshForm()
        {
            dateTimePicker1.Enabled = false;
            year = dateTimePicker1.Value.Year;
            month = dateTimePicker1.Value.ToString("MMMM");
            monthnum = dateTimePicker1.Value.Month;

            DataStuff ds = new DataStuff(monthnum, year);
            Money mon = new Money(monthnum);
            Initialize();
            dateTimePicker1.Enabled = true;
        }
        private void Initialize()
        {
            ClearListViews();
            PopulateIncome();
        }
        private void PopulateIncome()
        {
            income = new Income(Dates.Month_StringToInt(month));
            exp = new Expenses(Dates.Month_StringToInt(month));

            AddIncome();
            AddExpense();
            AddTotals();
        }

        public void ClearListViews()
        {
            lv_Income.Items.Clear();
            lv_Income.Groups.Clear();
            lv_Income.Columns.Clear();
        }

        private void AddIncome()
        {
            lv_Income.FullRowSelect = true;
            lv_Income.Columns.Add("", 150, HorizontalAlignment.Left);
            foreach (DateTime date in DataStuff.FridaysInMonth)
            {
                lv_Income.Columns.Add(date.ToShortDateString(), date_col_width, HorizontalAlignment.Left);
            }
            lv_Income.Columns.Add("Total", date_col_width, HorizontalAlignment.Right);
            lv_Income.Columns.Add("Budgeted", date_col_width, HorizontalAlignment.Right);
            System.Windows.Forms.ListViewGroup IncomeGroup =
                new System.Windows.Forms.ListViewGroup("Income", System.Windows.Forms.HorizontalAlignment.Left);
            lv_Income.Groups.Add(IncomeGroup);
            lv_Income.View = View.Details;

            foreach (string s in dbData.listIncomeCategories)
            {
                ListViewItem IncomeCat = new System.Windows.Forms.ListViewItem(s);
                IncomeCat.Group = IncomeGroup;
                lv_Income.Items.Add(IncomeCat);
                foreach (Dictionary<string, decimal> week in income.list_TransactionsByCategoryForWeek)
                {
                    IncomeCat.SubItems.Add(week[s].ToString(Money.MoneyFormat));
                }
                IncomeCat.SubItems.Add(DataStuff.CategoryTotals[s].ToString(Money.MoneyFormat));
            }
        }
        private void AddExpense()
        {
            System.Windows.Forms.ListViewGroup ExpenseGroup =
                new System.Windows.Forms.ListViewGroup("Expenses", System.Windows.Forms.HorizontalAlignment.Left);
            lv_Income.Groups.Add(ExpenseGroup);

            ListViewItem ExpenseCat = new System.Windows.Forms.ListViewItem("");
            ExpenseCat.Group = ExpenseGroup;

            foreach (string s in dbData.listExpenseCategories)
            {
                ExpenseCat = new System.Windows.Forms.ListViewItem(s);
                ExpenseCat.Group = ExpenseGroup;
                lv_Income.Items.Add(ExpenseCat);

                foreach (Dictionary<string, decimal> week in exp.list_TransactionsByCategoryForWeek)
                {
                    ExpenseCat.SubItems.Add(week[s].ToString(Money.MoneyFormat));
                }
                ExpenseCat.SubItems.Add(DataStuff.CategoryTotals[s].ToString(Money.MoneyFormat));
                ExpenseCat.SubItems.Add(dbData.CategoryBudgets[s].ToString(Money.MoneyFormat));
            }
        }
        private void AddTotals()
        {
            System.Windows.Forms.ListViewGroup TotalsGroup =
                new System.Windows.Forms.ListViewGroup("Totals", System.Windows.Forms.HorizontalAlignment.Left);
            lv_Income.Groups.Add(TotalsGroup);

            ListViewItem TotalCat = new System.Windows.Forms.ListViewItem("Incoming");
            TotalCat.Group = TotalsGroup;
            lv_Income.Items.Add(TotalCat);
            foreach (DateTime d in DataStuff.FridaysInMonth)
            {
                TotalCat.SubItems.Add(DataStuff.TotalsForWeekIncoming[d].ToString());
            }
            TotalCat.SubItems.Add(DataStuff.CategoryTotals["Incoming"].ToString(Money.MoneyFormat));
            TotalCat = new System.Windows.Forms.ListViewItem("Expenses");
            TotalCat.Group = TotalsGroup;
            lv_Income.Items.Add(TotalCat);
            foreach (DateTime d in DataStuff.FridaysInMonth)
            {
                TotalCat.SubItems.Add(DataStuff.TotalsForWeekOutGoing[d].ToString(Money.MoneyFormat));
            }
            TotalCat.SubItems.Add(DataStuff.CategoryTotals["Expenses"].ToString());
            TotalCat = new System.Windows.Forms.ListViewItem("Net");
            TotalCat.Group = TotalsGroup;
            lv_Income.Items.Add(TotalCat);
            foreach (DateTime d in DataStuff.FridaysInMonth)
            {
                TotalCat.SubItems.Add(DataStuff.TotalsForWeek[d].ToString(Money.MoneyFormat));
            }
            TotalCat.SubItems.Add(DataStuff.CategoryTotals["Net"].ToString(Money.MoneyFormat));
        }

        //Not in Use
        private void CreateMyListView()
        {
            // Create a new ListView control.
            ListView listView1 = new ListView();
            listView1.Bounds = new Rectangle(new Point(10, 10), new Size(400, 200));

            // Set the view to show details.
            listView1.View = View.Details;
            // Allow the user to edit item text.
            listView1.LabelEdit = true;
            // Allow the user to rearrange columns.
            listView1.AllowColumnReorder = true;
            // Display check boxes.
            listView1.CheckBoxes = true;
            // Select the item and subitems when selection is made.
            listView1.FullRowSelect = true;
            // Display grid lines.
            listView1.GridLines = true;
            // Sort the items in the list in ascending order.
            listView1.Sorting = SortOrder.Ascending;

            // Create three items and three sets of subitems for each item.
            ListViewItem item1 = new ListViewItem("item1", 0);
            // Place a check mark next to the item.
            item1.Checked = true;
            item1.SubItems.Add("1");
            item1.SubItems.Add("2");
            item1.SubItems.Add("3");
            ListViewItem item2 = new ListViewItem("item2", 1);
            item2.SubItems.Add("4");
            item2.SubItems.Add("5");
            item2.SubItems.Add("6");
            ListViewItem item3 = new ListViewItem("item3", 0);
            // Place a check mark next to the item.
            item3.Checked = true;
            item3.SubItems.Add("7");
            item3.SubItems.Add("8");
            item3.SubItems.Add("9");

            // Create columns for the items and subitems.
            // Width of -2 indicates auto-size.
            listView1.Columns.Add("Item Column", -2, HorizontalAlignment.Left);
            listView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left);
            listView1.Columns.Add("Column 3", -2, HorizontalAlignment.Left);
            listView1.Columns.Add("Column 4", -2, HorizontalAlignment.Center);

            //Add the items to the ListView.
            listView1.Items.AddRange(new ListViewItem[] { item1, item2, item3 });

            // Create two ImageList objects.
            ImageList imageListSmall = new ImageList();
            ImageList imageListLarge = new ImageList();

            // Initialize the ImageList objects with bitmaps.
            //imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage1.bmp"));
            //imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage2.bmp"));
            //imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage1.bmp"));
            //imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage2.bmp"));

            //Assign the ImageList objects to the ListView.
            listView1.LargeImageList = imageListLarge;
            listView1.SmallImageList = imageListSmall;

            // Add the ListView to the control collection.
            this.Controls.Add(listView1);
        }

        private void btnAddPurchase_Click(object sender, EventArgs e)
        {
            Add_Purchase add_purchase_form = new Add_Purchase();
            add_purchase_form.Show();
            //add_purchase_form.ShowDialog();
            //add_purchase_form.Dispose();
            RefreshForm();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            RefreshForm();
        }

        private void btnAddIncome_Click(object sender, EventArgs e)
        {
            ExpenseListByCategory expense_list_category = new ExpenseListByCategory();
            //expense_list_category.ShowDialog();
            //expense_list_category.Dispose();
            expense_list_category.Show();
            RefreshForm();
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            CategoryEdit category_edit = new CategoryEdit();
            //category_edit.ShowDialog();
            //category_edit.Dispose();
            category_edit.Show();
            RefreshForm();
        }

        //resize the grid view if we resize the main form
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if(Form1.ActiveForm != null)
            {
                lv_Income.Height = Form1.ActiveForm.Height - 51 - lv_Income.Location.Y;
                lv_Income.Width = Form1.ActiveForm.Width - 40;
            }
        }

        //double clicking on a category in the list launches the detail
        private void lv_Income_DoubleClick(object sender, EventArgs e)
        {
            string cat = lv_Income.SelectedItems[0].SubItems[0].Text;
            switch(cat)
            {
                case "Net":
                case "Incoming":
                case "Expenses":
                    return;
            }
            if(lv_Income.SelectedIndices[0] >= dbData.listIncomeCategories.Count)
            {
                ExpenseListByCategory expense_list_category = new ExpenseListByCategory(cat, 
                                                        new DateTime(dateTimePicker1.Value.Year,
                                                                     dateTimePicker1.Value.Month,1));
                expense_list_category.ShowDialog();
                expense_list_category.Dispose();
                RefreshForm();
            }
        }
        private string GetUserDataPath()
        {
            string s;
            if (ApplicationDeployment.IsNetworkDeployed)
            {
                s = ApplicationDeployment.CurrentDeployment.DataDirectory;
            }
            else
            {
                s = Application.StartupPath;
            }
            lblDataSource.Text = "Data Source: "+s;
            return s;
        }

        private void copyWorkingDBToDesktopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string deskpath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string destination = String.Format(@"{0}\{1}", deskpath, dbName.Replace(".", "_backup."));
                File.Delete(destination);
                File.Copy(String.Format(@"{0}\{1}", GetUserDataPath(), dbName)
                         , String.Format(@"{0}\{1}", deskpath, dbName.Replace(".", "_backup.")));
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Error copying: {0}", ex.Message));
            }
        }

        private void copyBackupOnDesktopToWorkingFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string deskpath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string destination = String.Format(@"{0}\{1}", GetUserDataPath(), dbName);
                string source = String.Format(@"{0}\{1}", deskpath, dbName.Replace(".", "_backup."));
                File.Delete(destination);
                File.Copy(source,destination);
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Error restoring from backup: {0}", ex.Message));
            }
        }

        private void btnYTD_Click(object sender, EventArgs e)
        {
            YearCategory ytd = new YearCategory();
            //ytd.ShowDialog();
            //ytd.Dispose();
            ytd.Show();
            //RefreshForm();
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            RefreshForm();
        }

        private void week_trans_detail_Click(object sender, EventArgs e)
        {
            TransactionDetail wtd = new TransactionDetail();
            //wtd.ShowDialog();
            //wtd.Dispose();
            wtd.Show();
            //RefreshForm();
        }

        private void btnBudget_Click(object sender, EventArgs e)
        {
            BudgetProgress bp = new BudgetProgress();
            //bp.ShowDialog();
            //bp.Dispose();
            bp.Show();
        }

        private void lv_Income_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void manualQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryExec qe = new QueryExec();
            qe.ShowDialog();
            qe.Dispose();
        }

        private void graphToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BarGraph g = new BarGraph();
            g.Show();
        }

        private void refreshFormToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshForm();
        }
        //private int WM_KEYDOWN = 0x100;
        

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //e.Handled = true;
            //switch (e.KeyChar)
            //{
            //    //case Keys.F5:
            //        RefreshForm();
            //        e.Handled = true;
            //        //break;
            //    default
            //        break;
            //}
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {

        }
    }
}
